package com.nyj.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.nyj.io.Resources;
import com.nyj.pojo.Configuration;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author niuyj
 * @date 2020/4/30 0:03
 * @description
 */
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        configuration = new Configuration();
    }

    //创建方法，利用dom4j解析InputStream对象，封装在Configuration对象中，返回
    public Configuration parseConfig(InputStream inputStream) {

        SAXReader reader = new SAXReader();
        Document document = null;

        try {
            document = reader.read(inputStream);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        //获取根节点<configuration>
        Element rootElement = document.getRootElement();
        //获取所有<property>节点
        List<Element> propertys = rootElement.selectNodes("//property");
        //遍历property节点，获取其中的name，value
            //定义Properties对象，将数据库配置信息写入Properties中
        Properties properties = new Properties();
        for (Element property : propertys) {
            String name = property.attributeValue("name");
            String value = property.attributeValue("value");
            properties.setProperty(name,value);
        }
        //定义连接池对象，用来生成Datasource对象
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        try {
            comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        // 设置Configuration对象DataSource属性值
        configuration.setDataSource(comboPooledDataSource);

        // 解析配置文件Mapper.xml，存储在MappedStatement对象中
        //获取mapper.xml文件路径
        List<Element> mapperPathList = rootElement.selectNodes("//mapper");
        //创建mapper.xml文件解析对象
        XMLMapperBuilder xMlMapperBuilder = new XMLMapperBuilder(configuration);
        for (Element mapperList : mapperPathList) {
            String mapperPath = mapperList.attributeValue("resource");
            InputStream input = Resources.getResourceAsStream(mapperPath);
            //解析mapper.xml文件
            xMlMapperBuilder.parse(input);
        }

        return configuration;
    }
}
